/**
 * Copyright (C) 2012 Chris Xinyue Zhao <hasszhao@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.code.lightlib.sample.fragment;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

import com.google.code.lightlib.sample.R;

import de.cellular.lib.lightlib.backend.LLImageResponse;
import de.cellular.lib.lightlib.backend.LLRequest;
import de.cellular.lib.lightlib.backend.LLRequestImage;
import de.cellular.lib.lightlib.backend.LLRequestImage.RequestedSize;
import de.cellular.lib.lightlib.backend.base.ILLRequestResponsible;
import de.cellular.lib.lightlib.backend.base.LLRequestResponsibleSimpleObject;
import de.cellular.lib.lightlib.ui.fragment.LLRequestingFragment;
import de.cellular.lib.lightlib.ui.view.gallery.LLAsyncGallery;
import de.cellular.lib.lightlib.ui.view.gallery.LLGallery;
import de.cellular.lib.lightlib.ui.view.gallery.LLGallery.CommentPosition;

/**
 * The Class ExampleSlideGallery that shows galleries to test.
 * 
 * @author Chris.Z <hasszhao@gmail.com>
 */
public class ExampleSlideGallery extends LLRequestingFragment implements LLGallery.OnItemClickListener,
        LLGallery.OnItemScrolledListener, LLGallery.OnItemScrollListener
{
//     private final static String[] SRC_URLs = {
//     "http://imgk.zol.com.cn/ideapad/3056/a3055449_s.jpg",
//     "http://imgk.zol.com.cn/ideapad/3056/a3055454_s.jpg",
//     "http://imgk.zol.com.cn/ideapad/3056/a3055446_s.jpg",
//     "http://imgk.zol.com.cn/ideapad/3056/a3055436_s.jpg",
//     };
    private final static String[] SRC_URLs = {
                                           "http://mobil.otto.de/ottoproj/wap/aktionen2012/kw26_24h_urlaub_1.jpg",
                                           "http://mobil.otto.de/ottoproj/wap/aktionen2012/kw26_material_girl.jpg",
                                           "http://mobil.otto.de/ottoproj/wap/aktionen2012/kw28_sandaletten.jpg",
                                           "http://mobil.otto.de/ottoproj/wap/aktionen2012/kw28_shorts_bermudas.jpg",
                                           "http://mobil.otto.de/ottoproj/wap/aktionen2012/kw27_catwalk.jpg",
                                           "http://mobil.otto.de/ottoproj/wap/aktionen2012/kw27_bss.jpg",
                                           };

    private ArrayList<Bitmap>     mBitmaps = new ArrayList<Bitmap>();

    private int                   mCur     = 0;
    private LLRequest             mRequest;
    private DisplayMetrics        metrics;
    private RequestedSize         mReqSize = new RequestedSize();
    private LLAsyncGallery        mAsyncGallery;

    @Override
    public void onPause() {
        super.onPause();
        if( mRequest != null ) {
            mRequest.abort();
            mRequest = null;
        }

        if( mAsyncGallery != null ) {
            mAsyncGallery.release();
        }
    }

    @Override
    public View onCreateView( LayoutInflater _inflater, ViewGroup _container, Bundle _savedInstanceState ) {
        View v = View.inflate( getActivity().getApplicationContext(), R.layout.ll_slide_gallery, null );
        metrics = new DisplayMetrics();
        ((WindowManager) getActivity().getSystemService( Context.WINDOW_SERVICE )).getDefaultDisplay().getMetrics(
                metrics );

        mReqSize.reqWidth = metrics.widthPixels;
        mReqSize.reqHeight = -1;

        if( getActivity() != null ) {
            getActivity().setProgressBarIndeterminateVisibility( true );
            getActivity().setProgressBarVisibility( true );
        }
        
        mRequest = LLRequestImage.start(
                getActivity().getApplicationContext(),
                new LLRequestResponsibleSimpleObject( (ILLRequestResponsible) this ),
                LLRequest.Method.GET,
                SRC_URLs[mCur],
                mReqSize,
                null );

        bindBitmapsAsynchronized( v, R.id.ll_empty_gallery );
        return v;
    }

    /**
     * Bind bitmaps asynchronized.
     * 
     * @param _v
     *            the view that contains the gallery.
     * @param _galleryId
     *            the id of gallery.
     */
    private void bindBitmapsAsynchronized( View _v, int _galleryId ) {
        mAsyncGallery = new LLAsyncGallery( (LLGallery) _v.findViewById( _galleryId ) );
        mAsyncGallery.setImages( SRC_URLs, mReqSize );
        mAsyncGallery.addComments(
                R.layout.ll_slide_gallery_comment,
                SRC_URLs );
        mAsyncGallery.setOnItemClickListener( this );
        mAsyncGallery.setOnItemScrollListener( this );
        mAsyncGallery.setOnItemScrolledListener( this );
    }

    /**
     * Update progressbar.
     */
    private void updateProgress() {
        if( getActivity() != null ) {
            int p = (int) ((++mCur) * (100.0 / SRC_URLs.length) * 100);
            getActivity().setProgress( p );
            if( p >= 10000 ) {
                getActivity().setProgressBarIndeterminateVisibility( false );
                getActivity().setProgressBarVisibility( false );
            }
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        if( getActivity() != null ) {
            getActivity().setProgressBarIndeterminateVisibility( false );
            getActivity().setProgressBarVisibility( false );
        }
    }

    /**
     * Bind bitmaps onto the gallery with some basic options.
     * 
     * @param _galleryId
     *            the of gallery.
     */
    private void bindBitmaps( int _galleryId ) {
        if( getView() != null ) {
            LLGallery gallery = (LLGallery) getView().findViewById( _galleryId );
            gallery.setImages( mBitmaps );
            gallery.setOnItemClickListener( this );
            gallery.setOnItemScrollListener( this );
            gallery.setOnItemScrolledListener( this );
        }
    }

    /**
     * Bind bitmaps with comment top.
     * 
     * @param _galleryId
     *            the id of gallery.
     */
    private void bindBitmapsWithCommentTop( int _galleryId ) {
        if( getView() != null ) {
            LLGallery gallery = (LLGallery) getView().findViewById( _galleryId );
            gallery.setImages( mBitmaps );
            gallery.setOnItemClickListener( this );
            gallery.setOnItemScrollListener( this );
            gallery.setOnItemScrolledListener( this );
            gallery.addComments(
                    R.layout.ll_slide_gallery_comment,
                    CommentPosition.TOP,
                    SRC_URLs );
        }
    }

    /**
     * Bind bitmaps with comment bottom.
     * 
     * @param _galleryId
     *            the id gallery.
     */
    private void bindBitmapsWithCommentBottom( int _galleryId ) {
        if( getView() != null ) {
            LLGallery gallery = (LLGallery) getView().findViewById( _galleryId );
            gallery.setImages( mBitmaps );
            gallery.setOnItemClickListener( this );
            gallery.setOnItemScrollListener( this );
            gallery.setOnItemScrolledListener( this );
            gallery.addComments( R.layout.ll_slide_gallery_comment,
                    SRC_URLs );
        }
    }

    @Override
    public void onItemClick( final int _location, final List<Bitmap> _bitmaps ) {
        // LLL.d( "clicked:" + _location );
        if( _location >= 0 && _bitmaps != null ) {
            DialogFragment dlg = new DialogFragment() {
                @Override
                public View onCreateView(
                        LayoutInflater _inflater,
                        ViewGroup _container,
                        Bundle _savedInstanceState ) {
                    getDialog().requestWindowFeature( Window.FEATURE_NO_TITLE );
                    View v = _inflater.inflate( R.layout.ll_show_popup_image, _container );
                    ImageView iv = (ImageView) v.findViewById( R.id.iv );
                    iv.setImageBitmap( _bitmaps.get( _location ) );
                    return v;
                }
            };
            dlg.show( getActivity().getSupportFragmentManager(), null );
        }
    }

    @Override
    public void onItemScroll( int _location, List<Bitmap> _bitmaps ) {
        // LLL.d( "Item is moving." );
    }

    @Override
    public void onItemScrolled( int _location, List<Bitmap> _bitmaps ) {
        // LLL.d( "Item is moved." );
    }

    @Override
    public void onRequestImageSuccessed( Message _msg ) {
        updateProgress();
        mBitmaps.add( ((LLImageResponse) _msg.obj).getBitmap() );
        if( mCur < SRC_URLs.length && getActivity() != null ) {
            mRequest = LLRequestImage.start(
                    getActivity().getApplicationContext(),
                    new LLRequestResponsibleSimpleObject( (ILLRequestResponsible) this ),
                    LLRequest.Method.GET,
                    SRC_URLs[mCur],
                    mReqSize,
                    null );
        }
        else {
            bindBitmapsWithCommentTop( R.id.ll_gallery );
            bindBitmaps( R.id.ll_auto_gallery );
            bindBitmaps( R.id.ll_triggerable_gallery );
            bindBitmapsWithCommentBottom( R.id.ll_big_gallery );
        }

    }

    @Override
    public void onRequestAborted( Message _msg ) {

    }

    @Override
    public void onRequestSuccessed( Message _msg ) {

    }

    @Override
    public void onRequestFailed( Message _msg ) {

    }

    @Override
    public void onRequestFinished( Message _msg ) {
    }

    @Override
    public void onRequestImageFailed( Message _msg ) {
    }
}
